package org.easy.eao.spring.schema;

import org.easy.eao.spring.SpringEaoFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedSet;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * EAO Bean 的 XML 分析器
 * @author Frank
 */
public class EaoBeanDefinitionParser implements BeanDefinitionParser {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		BeanDefinitionBuilder factory = BeanDefinitionBuilder.genericBeanDefinition(SpringEaoFactory.class);
		// 获取 EAO 接口类名
		String clazz = element.getAttribute(EaoSchemaNames.BEAN_ATTRIBUTE_INTERFACE);
		factory.addPropertyValue(SpringEaoFactory.ATTRIBUTE_CLAZZ, new TypedStringValue(clazz));
		// 获取该EAO私有的Action类型
		ManagedSet actions = new ManagedSet();
		NodeList nodeList = element.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node.getNodeType() != Node.ELEMENT_NODE)
				continue;
			Element e = (Element) node;
			if (!e.getLocalName().equals(EaoSchemaNames.ACTION_ELEMENT))
				continue;
			String name = e.getAttribute(EaoSchemaNames.ACTION_ATTRIBUTE_CLASS);
			actions.add(new TypedStringValue(name));
		}
		factory.addPropertyValue(SpringEaoFactory.ATTRIBUTE_ACTIONS, actions);
		return factory.getBeanDefinition();
	}

}
